package com.ahstu.learning.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.base.BaseActivity;
import com.ahstu.learning.bean.User;
import com.ahstu.learning.event.FinishEvent;
import com.ahstu.learning.friend.FriendTable;
import com.ahstu.learning.model.UserModel;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends BaseActivity {
    public static Tencent mTencent;
    private static String openId;
    @Bind(R.id.et_username)
    EditText et_username;
    @Bind(R.id.et_password)
    EditText et_password;
    @Bind(R.id.btn_login)
    Button btn_login;
    @Bind(R.id.tv_register)
    TextView tv_register;

    ProgressDialog progress;
    //    @Bind(R.id.qq_login)
    RelativeLayout QQLogin;
    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
        }
    };
    private long exitTime = 0;
    private UserInfo mInfo;

    public static void initOpenidAndToken(JSONObject jsonObject) {

        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mTencent = Tencent.createInstance("222222", this);
        QQLogin = (RelativeLayout) findViewById(R.id.qq_login);
        QQLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTencent.login(LoginActivity.this, "all", loginListener);
            }
        });
        init();

    }

    @OnClick(R.id.btn_login)
    public void onLoginClick(View view) {
        UserModel.getInstance().login(et_username.getText().toString(), et_password.getText().toString(), new LogInListener() {

            @Override
            public void done(Object o, final BmobException e) {
                progress = new ProgressDialog(LoginActivity.this);
                progress.setMessage("登录中，请稍后");
                progress.setCanceledOnTouchOutside(false);
                progress.show();
                if (e == null) {
                    User user = (User) o;
                    //更新当前用户资料
                    BmobIM.getInstance().updateUserInfo(new BmobIMUserInfo(user.getObjectId(), user.getUsername(), user.getAvatar()));
                    SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username", et_username.getText().toString());
                    editor.commit();
                    startActivity(MainActivity.class, null, true);
                } else {
                    progress.dismiss();
                    User user = new User();
                    BmobQuery<User> query = new BmobQuery<User>();
                    query.addWhereEqualTo("username", et_username.getText().toString());
                    query.findObjects(LoginActivity.this, new FindListener<User>() {
                        @Override
                        public void onSuccess(List<User> list) {
                            if (list.isEmpty()) {
                                toast("账户不存在");
                                et_username.setText("");
                            } else if (e.getErrorCode() == 101) {
                                toast("密码不正确，请重新输入");
                            } else
                                toast(e.getMessage());
                        }

                        @Override
                        public void onError(int i, String s) {
                            toast("请检查您的网络");
                        }
                    });

                }
            }
        });
    }

    @OnClick(R.id.tv_register)
    public void onRegisterClick(View view) {
        startActivity(RegisterActivity.class, null, false);
    }

    @Subscribe
    public void onEventMainThread(FinishEvent event) {
        finish();
    }

    // 动画效果
    private void init() {
        Animation anim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.login_anim);
        anim.setFillAfter(true);
        findViewById(R.id.user).startAnimation(anim);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(LoginActivity.this, "再按一次退出登录", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, SplashActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTencent = null;
        loginListener = null;
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            JSONObject jsonResponse = (JSONObject) response;
            if ((null != jsonResponse && jsonResponse.length() == 0) || null == response) {
                Util.showResultDialog(LoginActivity.this, "返回为空", "登录失败");
                return;
            }
//            Toast.makeText(LoginActivity.this, "账号登录成功", Toast.LENGTH_SHORT).show();
            progress = new ProgressDialog(LoginActivity.this);
            progress.setMessage("登录中，请稍后");
            progress.setCanceledOnTouchOutside(false);
            progress.show();
            doComplete((JSONObject) response);
            final User qquser = new User();
            final String username = "qq" + openId.substring(0, 4);

            qquser.setUsername(username);
            qquser.setPassword(openId);
            qquser.setOpenId(openId);
            qquser.signUp(LoginActivity.this, new SaveListener() {

                @Override
                public void onSuccess() {
                    SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username", username);
                    editor.commit();

                    EventBus.getDefault().post(new FinishEvent());

                    //添加好友功能实现成功
                    FriendTable friendTableMy = new FriendTable();
                    FriendTable friendTableFriend = new FriendTable();

                    friendTableMy.setMyName(username);
                    friendTableMy.setFriendName("客服");

                    friendTableFriend.setMyName("客服");
                    friendTableFriend.setFriendName(username);
                    //更新我的好友列表
                    friendTableMy.save(LoginActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                        }

                        @Override
                        public void onFailure(int i, String s) {
                        }
                    });

                    //更新被加的账号的好友列表
                    friendTableFriend.save(LoginActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                        }

                        @Override
                        public void onFailure(int i, String s) {
                        }
                    });
                    
                    startActivity(MainActivity.class, null, true);
                }

                @Override
                public void onFailure(int i, String s) {
//                    账户已注册
                    if (i == 202) {
                        UserModel.getInstance().login("qq" + openId.substring(0, 4), openId, new LogInListener() {

                            @Override
                            public void done(Object o, final BmobException e) {
                                if (e == null) {
                                    User user = (User) o;
                                    //更新当前用户资料
                                    BmobIM.getInstance().updateUserInfo(new BmobIMUserInfo(user.getObjectId(), user.getUsername(), user.getAvatar()));
                                    SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
                                    SharedPreferences.Editor editor = sp.edit();
                                    editor.putString("username", username);
                                    editor.commit();
                                    startActivity(MainActivity.class, null, true);
                                    finish();
                                }
                            }
                        });
                    } else
                        progress.dismiss();

                }
            });

        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
            Util.toastMessage(LoginActivity.this, "登录异常");
            Util.dismissDialog();
        }

        @Override
        public void onCancel() {
            Util.toastMessage(LoginActivity.this, "取消登录");
            Util.dismissDialog();
        }
    }
}
